package io.gitee.wiqer.medium;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ConcurrentSkipListMap;

public class SolutionNC119_GetLeastNumbers {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> arr =new ArrayList<Integer>();
        ConcurrentSkipListMap<Integer,  Integer> source =new ConcurrentSkipListMap<Integer,  Integer>();
        for(Integer i:input){
            Integer r=source.get(i);
            if(r==null){
                r=0;
            }
            r++;
            source.put(i,r);
        }
        if(k>input.length||input.length==0){
            return arr;
        }
        try {
            source.forEach((key, value) -> {

                while (value-->0){
                    if(arr.size()>=k){
                        throw new IllegalArgumentException("");
                    }
                    arr.add(key);
                }

            });
        }catch (Exception e) {

        }

        return  arr;

    }
    public ArrayList<Integer> GetLeastNumbers_Solution_Old(int [] input, int k) {
        ArrayList<Integer> arr =new ArrayList<Integer>();
        ArrayList<Integer> source =new ArrayList<Integer>();
        for(Integer i:input){
            source.add(i);
        }
        if(k>input.length||input.length==0){
            return arr;
        }

        while (arr.size()<k){
            Integer min=source.get(0);
            Iterator<Integer> iter = source.iterator();
            while(iter.hasNext()){
                Integer i = iter.next();
                if(min>=i) {
                    min=i;
                }
            }
            arr.add(min);
            source.remove(min);
        }

        return  arr;

    }

}
